import csv
from functools import reduce
from app.models.Poetry import Poetry, PoetryCN, PoetryTypeCN


def transform_bak(poetry: dict) -> dict:
    for key in poetry:
        val = poetry[key]
        if type(val) is list:
            newVal = reduce(lambda acc, item: acc + item.get("value", ""), val, "")
            poetry[key] = newVal
    return poetry

def transform(poetry: dict, poetryType: PoetryTypeCN = PoetryTypeCN.宋词) -> dict:
    poetry["类型"] = poetryType.value
    for key in poetry:
        val = poetry[key]
        if type(val) is list:
            newVal = reduce(lambda acc, item: acc + item.get("value", ""), val, "")
            poetry[key] = newVal
    return poetry


def transformToEntity(poetry: dict, poetryType: PoetryTypeCN = PoetryTypeCN.宋词) -> PoetryCN:
    for key in poetry:
        val = poetry[key]
        if type(val) is list:
            newVal = reduce(lambda acc, item: acc + item.get("value", ""), val, "")
            poetry[key] = newVal
    return PoetryCN(**poetry, 类型=poetryType)


def save_to_csv(poetries: list, filename: str):
    if not poetries:
        print("No poetries to save.")
        return

    # Use field names from the Venue model
    fieldnames = PoetryCN.model_fields.keys()
    with open(filename, mode="w", newline="", encoding="utf-8") as file:
        writer = csv.DictWriter(file, fieldnames=fieldnames, delimiter="\t")
        writer.writeheader()
        writer.writerows(poetries)
    print(f"Saved {len(poetries)} poetries to '{filename}'.")


def save_to_csv_bak(poetries: list, filename: str):
    if not poetries:
        print("No poetries to save.")
        return

    # Use field names from the Venue model
    fieldnames = Poetry.model_fields.keys()
    
    with open(filename, mode="w", newline="", encoding="utf-8") as file:
        writer = csv.DictWriter(file, fieldnames=fieldnames, delimiter="\t")
        writer.writeheader()
        writer.writerows(poetries)
    print(f"Saved {len(poetries)} poetries to '{filename}'.")
